<template>
    <div id="app">
        {{ successChunk }}
        <img alt="Vue logo" src="./assets/logo.png" />
        <HelloWorld></HelloWorld>
        <input type="file" ref="uploadInput" @input="computeMD5">
    </div>
</template>

<script>
import SparkMD5 from 'spark-md5';
import md5 from 'md5';
// import HelloWorld from './components/HelloWorld.vue'
export default {
    name: 'App',
    // components: {HelloWorld},
    data() {
        return {
            chunkList: [], //对文件进行分片处理后，储存的数组
            successChunk: 0, //判断片段是否都上传成功
        };
    },
    methods: {
        computeMD5(e) {
          let file = e.target.files[0];
            const _this = this;
            return new Promise((resolve, reject) => {
                try {
                    let fileReader = new FileReader();
                    let blobSlice = File.prototype.slice;
                    let currentChunk = 0; // 当前第几片
                    const chunkSize = 8 * 1024 * 1024; // 每片的大小，这里是5M
                    let chunks = Math.ceil(file.size / chunkSize); // 总片数
                    let spark = new SparkMD5.ArrayBuffer();
                    let md5Arr = [];
                    let loadNext = () => {
                        let start = currentChunk * chunkSize;
                        let end = start + chunkSize >= file.size ? file.size : start + chunkSize;
                        fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
                        _this.chunkList.push(blobSlice.call(file, start, end)); // 将每次分片的字节流放到数组里
                    };
                    loadNext();
                    fileReader.onload = e => {
                        spark.append(e.target.result); //插件计算MD5
                        md5Arr.push(md5(e.target.result))
                        currentChunk++;
                        if (currentChunk < chunks) {
                            loadNext();
                        } else {
                            this.md5 = spark.end();
                            console.log(md5Arr[md5Arr.length-1], this.md5);
                            resolve(this.md5);
                        }
                    };
                    fileReader.onerror = function () {
                        this.$message.error(`文件${file.name}读取出错，请检查该文件`);
                    };
                } catch (e) {
                    reject(e);
                }
            });
        },
    },
};
</script>

<style>
#app {
    font-family: Avenir, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
}
</style>
